/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.app.manager.classloader;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Leon Huo
 * @Date: 2021/5/20
 */
public class ClassManager {

    private final Map<String, String> nameAppMap = new HashMap<>();
    private final Map<String, Class<?>> nameClassMap = new HashMap<>();
    private final Map<String, Set<Class<?>>> appClassMap = new HashMap<>();
    private final Map<String, Set<String>> appNameMap = new HashMap<>();
    private final Lock lock = new ReentrantLock();

    public ClassManager() {
    }

    /**
     * 根据类名称获取Class实例
     *
     * @param name
     * @return
     */
    public Class<?> getClass(String name) {
        return nameClassMap.get(name);
    }

    /**
     * 根据类名称获取application名称
     *
     * @param className
     * @return
     */
    public String getAppName(String className) {
        return nameAppMap.get(className);
    }

    /**
     * 获取某个App下的所有Class
     * 注意这里一定要使用加锁的拷贝方法 否则由于hashmap的线程不安全性 可能会throw ConcurrentModificationException
     * 下同
     *
     * @param appName
     * @return
     */
    public Set<Class<?>> getAppClasses(String appName) {
        try {
            lock.lock();
            return new HashSet<>(this.appClassMap.getOrDefault(appName, Collections.emptySet()));
        } finally {
            lock.unlock();
        }
    }

    /**
     * 获取某个App下的所有类名称
     *
     * @param appName
     * @return
     */
    public Set<String> getAppClassNames(String appName) {
        try {
            lock.lock();
            return new HashSet<>(this.appNameMap.getOrDefault(appName, Collections.emptySet()));
        } finally {
            lock.unlock();
        }
    }

    /**
     * 获取管理器持有的所有Class名称
     *
     * @return
     */
    public Set<String> getAllClassNames() {
        try {
            lock.lock();
            return new HashSet<>(this.nameClassMap.keySet());
        } finally {
            lock.unlock();
        }
    }

    /**
     * 获取管理器持有的所有Class对象
     *
     * @return
     */
    public Set<Class<?>> getAllClasses() {
        try {
            lock.lock();
            Set<Class<?>> set = new HashSet<>(this.nameClassMap.values());
            set.remove(null);
            return set;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 获取class数量
     *
     * @return
     */
    public Integer getClassCount() {
        return this.nameClassMap.size();
    }

    /**
     * 在管理器中注册一个Class
     *
     * @param className
     * @param clazz
     * @param appName
     * @return
     */
    public boolean registryClass(String className, Class<?> clazz, String appName) {
        try {
            lock.lock();
            nameAppMap.put(className, appName);
            nameClassMap.put(className, clazz);

            Set<Class<?>> classSet = appClassMap.getOrDefault(appName, new HashSet<>());
            if (clazz != null) {
                classSet.add(clazz);
            }

            appClassMap.put(appName, classSet);

            Set<String> nameSet = appNameMap.getOrDefault(appName, new HashSet<>());
            nameSet.add(className);
            appNameMap.put(appName, nameSet);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            lock.unlock();
        }

        return true;
    }

    public boolean removeApp(String appName) {
        try {
            lock.lock();
            Set<String> nameSet = appNameMap.getOrDefault(appName, new HashSet<>());

            for (String name : nameSet) {
                nameAppMap.remove(name);
                nameClassMap.remove(name);
            }

            appNameMap.remove(appName);
            appClassMap.remove(appName);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            lock.unlock();
        }

        return true;
    }
}
